package com.ysxsoft.wdg.ui.activity.order;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.UserInfoBean;
import com.ysxsoft.wdg.bean.response.PingResponse;
import com.ysxsoft.wdg.bean.response.ShouResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ListObserverMap;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.ERatingBar;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

public class PinOrderPlActivity extends BaseActivity implements BGASortableNinePhotoLayout.Delegate {


    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.rating)
    ERatingBar rating;
    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.btn_sure)
    TextView btn_sure;
    @BindView(R.id.bottomLayout)
    LinearLayout bottomLayout;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;
    @BindView(R.id.ninePhotoLayout)
    BGASortableNinePhotoLayout mPhotosSnpl;
    private String productId;
    private String orderId;
    private static final int PRC_PHOTO_PICKER = 1;
    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int RC_PHOTO_PREVIEW = 2;
    private int type;
    private boolean isZy=false;//是否是满减

    public static void start(Activity context,  String productId, String orderId, int type,boolean isZy) {
        Intent intent = new Intent(context, PinOrderPlActivity.class);
        intent.putExtra("productId", productId);
        intent.putExtra("orderId", orderId);
        intent.putExtra("type", type);
        intent.putExtra("isZy", isZy);
        context.startActivity(intent);
    }

    public static void start(Activity context, String companyId, String productId, String orderId, int type) {
        Intent intent = new Intent(context, PinOrderPlActivity.class);
        intent.putExtra("companyid", companyId);
        intent.putExtra("productId", productId);
        intent.putExtra("orderId", orderId);
        intent.putExtra("type", type);
       context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_zy_order_pl;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        titleContent.setText("评价");
        productId = getIntent().getStringExtra("productId");//0自营商城
        companyid = getIntent().getStringExtra("companyid");//实体商城id
        orderId=getIntent().getStringExtra("orderId");
        type = getIntent().getIntExtra("type", 0);//0自营商城/满减商城  1实体商城
        isZy=getIntent().getBooleanExtra("isZy",false);//type为0 可能是自营可能是满减    isZy用来区分两者
        bottomLayout.setVisibility(View.GONE);
        mPhotosSnpl.setVisibility(View.GONE);//隐藏图片上传
        initSnpl();
    }

    /**
     * 初始化九宫格图片控件
     */
    private void initSnpl() {
        //设置最大选择张数
        mPhotosSnpl.setMaxItemCount(9);
        //设置是否可编辑
        mPhotosSnpl.setEditable(true);
        //显示九图控件的加号按钮
        mPhotosSnpl.setPlusEnable(true);
        //是否可拖拽排序
        mPhotosSnpl.setSortable(true);
        //设置拖拽排序控件的代理
        mPhotosSnpl.setDelegate(this);
    }

    @Override
    protected void setListener() {

    }


    @OnClick({R.id.title_finish, R.id.btn_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.btn_sure:
                if (type == 0) {//0自营商城 满减商城 1实体商城
                    upload();
                } else {
                    upload();
                }
                break;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case 0x02:
                    ArrayList<String> list = mPhotosSnpl.getData();
                    if (p < list.size()) {
                        File file = new File(list.get(p));
                        p++;
                        commit(file.getPath());
                    } else {
                        isUpload = false;
                        p=0;
                        if (type == 0) {
                            ping1();//评价自营/满减
                        } else {
                            ping2();//评价商品
                        }
                    }
                    break;
            }
        }
    };
    private int p = 0;
    private boolean isUpload = false;

    private void upload() {
        if (!isUpload) {
            multStatusView.showLoading();
            ids.clear();
            p = 0;
            isUpload = true;
            handler.sendEmptyMessage(0x02);
        }
    }

    /**
     * 九宫格控件
     * 点击添加加号按钮执行的方法
     *
     * @param sortableNinePhotoLayout
     * @param view
     * @param position
     * @param models
     */
    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    /**
     * 九宫格控件
     * 点击删除按钮执行的方法
     *
     * @param sortableNinePhotoLayout
     * @param view
     * @param position
     * @param model
     * @param models
     */
    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        mPhotosSnpl.removeItem(position);
    }

    /**
     * 九宫格控件
     * 点击图片进入预览界面
     *
     * @param sortableNinePhotoLayout
     * @param view
     * @param position
     * @param model
     * @param models
     */
    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        Intent photoPickerPreviewIntent = new BGAPhotoPickerPreviewActivity.IntentBuilder(this)
                .previewPhotos(models) // 当前预览的图片路径集合
                .selectedPhotos(models) // 当前已选中的图片路径集合
                .maxChooseCount(mPhotosSnpl.getMaxItemCount()) // 图片选择张数的最大值
                .currentPosition(position) // 当前预览图片的索引
                .isFromTakePhoto(false) // 是否是拍完照后跳转过来
                .build();
        startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
    }

    /**
     * 九宫格控件
     * 拖拽排序发生变法执行的方法
     *
     * @param sortableNinePhotoLayout
     * @param fromPosition
     * @param toPosition
     * @param models
     */
    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {
        //排序发生变化
    }

    /**
     * 九宫格控件
     * 图片选择对调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) {
            mPhotosSnpl.addMoreData(data.getStringArrayListExtra("EXTRA_SELECTED_PHOTOS"));
        } else if (requestCode == RC_PHOTO_PREVIEW) {
            mPhotosSnpl.setData(data.getStringArrayListExtra("EXTRA_SELECTED_PHOTOS"));
        }
    }


    /**
     * 九宫格控件
     * 添加图片，申请权限
     */
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");

        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(this)
                .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                .maxChooseCount(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择张数的最大值
                .selectedPhotos(null) // 当前已选中的图片路径集合
                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                .build();
        startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
    }

    private String pic = "";

    /**
     * 自营商品/满减商品评价
     */
    private void ping1() {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < ids.size(); i++) {
            if (i == ids.size() - 1) {
                stringBuffer.append(ids.get(i));
            } else {
                stringBuffer.append(ids.get(i) + ",");
            }
        }
        OkHttpUtils.post()
                .url(UrlHost.PING_PRODUCT)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("content", etInput.getText().toString())
                .addParams("productid", productId)//商品id
                .addParams("orderid", orderId)//订单id
                .addParams("pic", stringBuffer.toString())//评论图片
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    PingResponse pingResponse = JsonUtils.parseByGson(response, PingResponse.class);
                    if (pingResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(pingResponse.getCode())) {
                        ToastUtils.showToast(pingResponse.getMs());

                        if(isZy){//是自营
                            ListObserverMap.notifyPing("OrderZyFragment");
                        }else{
                            ListObserverMap.notifyPing("OrderMjFragment");
                        }
                        finish();
                    } else {
                        ToastUtils.showToast(pingResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    private String companyid="";

    /**
     * 实体商城商品评价
     */
    private void ping2() {
//        uid  companyid  score  content  pic
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < ids.size(); i++) {
            if (i == ids.size() - 1) {
                stringBuffer.append(ids.get(i));
            } else {
                stringBuffer.append(ids.get(i) + ",");
            }
        }

        OkHttpUtils.post()
                .url(UrlHost.PING_ST_PRODUCT)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("score", rating.getStarCount() + "")
                .addParams("content", etInput.getText().toString())
                .addParams("companyid", companyid)//店铺id
                .addParams("productid", productId)//商品id
                .addParams("orderid",orderId)//订单id
                .addParams("pic", stringBuffer.toString())//图片
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    ShouResponse shouResponse = JsonUtils.parseByGson(response, ShouResponse.class);
                    if (shouResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(shouResponse.getCode())) {
                        ToastUtils.showToast(shouResponse.getMs());
                        ListObserverMap.notify("OrderStFragment");
                        finish();
                    } else {
                        ToastUtils.showToast(shouResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    private List<String> ids = new ArrayList<>();

    private void commit(String path) {
        mApiHelper.commitPic(path, new Observer<BaseBean<UserInfoBean>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseBean<UserInfoBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    ids.add(baseBean.getData().getId());
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
                handler.sendEmptyMessage(0x02);
            }

            @Override
            public void onError(Throwable e) {
                handler.sendEmptyMessage(0x02);
            }

            @Override
            public void onComplete() {
            }
        });
    }
}
